<template>
  <div>


    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm','yes','add')" v-if="crFlag">发布</el-button>
        <el-button @click="submitForm('ruleForm','yes','update')" v-if="saveFlag">保存</el-button>
        <el-button @click="resetForm('ruleForm')">返回</el-button>
      </el-form-item>


      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title" autocomplete="false" placeholder="请输入标题"></el-input>
      </el-form-item>

      <el-form-item label="描述">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入描述"
          v-model="artical.descre"
        >
        </el-input>
      </el-form-item>



      <el-form-item label="资源链接">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入资源链接"
          v-model="artical.resourceLink"
        >
        </el-input>
      </el-form-item>

      <el-form-item label="频道" prop="channelId">
<!--        <el-input placeholder="选择频道" v-model="ruleForm.channelId" class="input-with-select" :disabled="true">-->
<!--          <el-select v-model="ruleForm.channelId" slot="prepend" placeholder="请选择">-->
<!--            <el-option v-for="(item,index) in channelSelect" :key="item.id" :value="item.id">{{item.id+":"+item.channelName}}</el-option>-->
<!--          </el-select>-->
<!--        </el-input>-->
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group
          v-model="checkedCities"
          @change="handleCheckedCitiesChange"
        >
          <el-checkbox
            v-for="city in cities"
            :label="city.id"
            :key="city.id"
          >
            {{city.channelName}}
          </el-checkbox>
        </el-checkbox-group>

      </el-form-item>

      <el-form-item label="资源文件">

        <!--        <uploadText @func="getTxtUrl" ref="uploadText"></uploadText>-->
        <uploadCard upType="选取文本/种子文件"
                    :listType="uploadParam.LIST_TYPE_TEXT"
                    :tip="uploadParam.TIP_TEXT"
                    @func="getTxtUrl"
                    ref="uploadText"


        ></uploadCard>

      </el-form-item>

      <el-form-item label="封面展示">
        <uploadCard @func="getPreUrl" ref="uploadPre"
                    upType="选取封面"
                    :limit="1"
                    :listType="uploadParam.LIST_TYPE_PICTURE_CARD"
                    :tip="uploadParam.TIP_PICTURE"


        ></uploadCard>
      </el-form-item>


      <el-form-item label="图片展示">
        <uploadCard @func="getImgUrl" ref="uploadCard"
                    upType="选取图片"
                    :listType="uploadParam.LIST_TYPE_PICTURE_CARD"
                    :tip="uploadParam.TIP_PICTURE"


        ></uploadCard>
      </el-form-item>

      <el-button type="primary" @click="submitForm('ruleForm','yes','add')" v-if="crFlag">发布</el-button>
      <el-button @click="submitForm('ruleForm','yes','update')" v-if="saveFlag">保存</el-button>
      <el-button @click="resetForm('ruleForm')">返回</el-button>


    </el-form>

  </div>

</template>
<script>
  /**
   * 多选框的构造 https://blog.csdn.net/qq_34707272/article/details/105344271
   */
  import {Artical} from '../req/Artical'
  import {StringUtil} from "../../utils/StringUtil";
  import uploadCard from "../../components/UploadCard"
  import uploadText from "../../components/UploadCard"
  import uploadPre from '../../components/UploadCard';
  import {ResultStatus} from "../constant/ResultStatus";
  import {UploadParam} from "../constant/UploadParam";
  import {Handle} from "../constant/Handle";
  import {ContentType} from "../constant/ContentType";
  import {BasePageReq} from "../admin/req/BasePageReq";
  let artical = new Artical();
  let cityOptions = [

  ];
  export default {
    data() {

      var validateTitle = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入标题'));
        }
        callback();
      };
      // var validateChannel = (rule, value, callback) => {
      //   if (value.length ==0 || value == null ) {
      //     callback(new Error('请输入选择频道'));
      //   }
      //   callback();
      // };


      return {
        inputFlat: true,
        artical,
        ruleForm: {
          title: '',
          channelId:this.checkedCities,
        },
        rules: {
          title: [
            {validator: validateTitle, trigger: 'blur'}
          ],
          // channelId:[
          //   {validator: validateChannel, trigger: 'blur'}
          // ],
        },
        uploadParam: UploadParam,//上传参数
        handle: this.$route.query.handle, //接收的处理
        id: this.$route.query.id,//接受的id
        saveFlag: true, //保存的开关
        crFlag: true,//创建的开关


        checkAll: false,
        checkedCities: [],
        cities: [],
        isIndeterminate: true

      };

    },

    methods: {

      /**
       * 获取上传组件的回传url
       * @param data
       */
      getImgUrl: function (data) {

        this.artical.imgs = data;

      },
      /**
       * 获取文档上传地址
       * @param data
       */
      getTxtUrl: function (data) {

        this.artical.resourceFile = data;

      },
      /**
       * 获取文档上传地址
       * @param data
       */
      getPreUrl: function (data) {

        this.artical.preImg = data.split("&&")[0];

      },
      /**
       * 提交
       * @param formName
       * @param isSend
       */
      submitForm: async function (formName, isSend,handler) {
        this.$refs[formName].validate((valid) => {
          if (!valid) {
            console.log('error submit!!');
            this.inputFlat = false;
            return false;
          }
        });
        if (!this.inputFlat) {
          return;
        }
        if(this.checkedCities == null || this.checkedCities.length == 0){
          this.$notify(StringUtil.warning("请选择频道"));
          return ;
        }


        //调用上传组件的方法
        await this.$refs.uploadCard.submitUpload();
        await this.$refs.uploadText.submitUpload();
        await this.$refs.uploadPre.submitUpload();


        this.artical.handle = handler;
        this.artical.title = this.ruleForm.title;
        this.artical.isSend = isSend;
        this.artical.channelId = this.checkedCities;

        this.$axios({
          method: 'post',
          url: 'artical/save',
          data: JSON.stringify(this.artical),
          datatype: 'json',
          headers: {
            'content-type': 'application/json;charset=UTF-8'
          },
        }).then((response) => {

          let datas = response.data;
          if (datas.code == ResultStatus.SUCCESS) {
            this.$notify(StringUtil.success(datas.msg));
            this.$router.push({name: 'articalManage'})
          } else {
            this.$notify(StringUtil.warning(datas.msg));
            return;
          }

        }).catch(function (error) {
          console.log(error)
          alert(error.data.msg);
          return false;
        });

      },
      resetForm(formName) {
        this.$router.push({name: 'articalManage'})
      },
      /**
       * 获取频道详情
       * @param id
       */
      getDetail(id) {
        this.artical.handle = Handle.QUERY;
        this.artical.id = id;

        this.$axios
          .post('/artical/save',
            this.artical, //转成json
            ContentType.APPLICATION_JSON,
          )
          .then((response) => {

            let datas = response.data;
            if (datas.code != ResultStatus.SUCCESS) {
              this.$notify(StringUtil.warning(datas.msg));
              return;
            }
            this.artical = datas.data;
            this.ruleForm.title = this.artical.title;
            this.checkedCities = datas.data.channelList.map(item=>{
              return item.channelId;
            })
            //


            //调取图片组件的方法
            this.$refs.uploadText.receiveFileList(this.artical.resourceFile);
            this.$refs.uploadPre.receiveFileList(this.artical.preImg);
            this.$refs.uploadCard.receiveFileList(this.artical.imgs);


          })
          .catch((error) => {
            console.log(error);
            let datas = error.data;
            this.$notify(StringUtil.warning(datas.msg));
          })
      },
      /**
       * 组件初始化设置
       * @param data
       */
      initDefault(data) {
        switch (data) {

          case Handle.UPDATE:
            this.crFlag = false;
            break;
          case Handle.ADD:
            this.saveFlag = false;
            break;

          default:
            break;
        }
      },
      /**
       * 加载频道
       */
      loadChannel(){
        let basePageReq = new BasePageReq();
        basePageReq.size=1000;
        basePageReq.page = 1;

        this.$axios
          .post('/channel/queryPage',
            basePageReq, //转成json
            ContentType.APPLICATION_JSON,
          )
          .then((response)=>{
            let datas = response.data;
            if(datas.code != ResultStatus.SUCCESS){
              this.$notify(StringUtil.warning(datas.msg));
              return;
            }
            let datas2 = datas.data;
            this.cities = datas2.list;


          })
          .catch((error)=>{
            console.log(error);
            let datas = error.data;
            this.$notify(StringUtil.warning(datas.msg));
          })


    },
      handleCheckAllChange(val) {
        let checked = this.cities.map(item => {
          return item.id;
        });
        this.checkedCities = val ? checked : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.cities.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
      }
    },
    components: {
      uploadCard,
      uploadText,
      uploadPre,
    },
    mounted() {
      //根据传来的handle进入组件默认值设计
      this.initDefault(this.handle);
      //这个方法会导致检验失效，找了半天。
      if (this.handle != null  && this.handle != Handle.ADD ) {
        this.getDetail(this.id);
      }
     this.loadChannel();
    },
  }
</script>

<style>
  #register{
    width: 50%  }
  .el-select .el-input {
    width: 130px;
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
</style>

